<template>
  <!-- 消防设施 -- 消防器材 -- 添加消防器材 -->
  <view class="addFireFighting">
    <view class="wrapper">
      <view class="wrapper-item">
        <u-cell :titleStyle="titleStyle" title="器材类型" clickable isLink :rightIconStyle="rightIconStyle"
          @click="cellClick('text', 'deviceType')">
          <text slot="icon" class="required">*</text>
          <view slot="value" :class="form.deviceTypeDesc ? 'cell-noEmpty' : 'cell-empty'">
            {{ form.deviceTypeDesc || "请选择" }}
          </view>
        </u-cell>

        <u-cell :titleStyle="titleStyle" title="器材数量（个）">
          <text slot="icon" class="required">*</text>
          <u-input v-model="form.deviceCount" data-type="workPerson" placeholder="请输入" slot="value" fontSize="14"
            placeholderClass="placeholderClass" inputAlign="right" border="none" :maxlength="3" :required="true"
            @blur="connumBlur"></u-input>
        </u-cell>

        <u-cell :titleStyle="titleStyle" title="器材编号">
          <text slot="icon" style="width: 15rpx"></text>
          <u-input v-model="form.deviceNo" data-type="workPerson" placeholder="请输入" slot="value" fontSize="14"
            placeholderClass="placeholderClass" inputAlign="right" border="none" :maxlength="3"
            :required="true"></u-input>
        </u-cell>

        <u-cell :titleStyle="titleStyle" title="器材过期时间" clickable isLink :rightIconStyle="rightIconStyle">
          <text slot="icon" style="width: 15rpx"></text>
          <view slot="value" data-type="expirationTimeName" @click="cellTimeClick"
            :class="form.expirationTimeName ? 'cell-noEmpty' : 'cell-empty'">
            {{ form.expirationTimeName || "请选择" }}
          </view>
        </u-cell>

        <u-cell :titleStyle="titleStyle" title="器材照片" :border="false">
          <text slot="icon" class="required">*</text>
        </u-cell>
        <view class="upload-view">
          <u-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" name="file" :maxCount="1" width="96"
            height="90">
            <image :src="baseImgUrl + 'upload-icon.png'" style="width: 192rpx; height: 180rpx"></image>
          </u-upload>
        </view>
      </view>
    </view>

    <view class="btns">
      <button class="reset-btn lt cancelBtn" type="primary" @click="navBack()">
        取消
      </button>
      <button class="submit-btn" type="primary" @click="sunmitHandle">
        保存
      </button>
    </view>

    <u-picker v-if="pickerShow" :show="pickerShow" :columns="columns" :keyName="keyName" @confirm="showConfirm"
      @close="pickerClose" @cancel="pickerCancel" :closeOnClickOverlay="true"></u-picker>

    <!-- 时间选择器 -->
    <u-datetime-picker ref="datetimePicker" :show="datetimeShow" v-model="timeValue" mode="date" :formatter="formatter"
      :minDate="minDate" :maxDate="maxDate" @close="pickerTimeClose" @cancel="pickerTimeClose(1)"
      @confirm="showTimeConfirm" :closeOnClickOverlay="true"></u-datetime-picker>
  </view>
</template>

<script>
  import {
    findEnableDictItemsbyCode
  } from "@/api/api.js";
  import {
    handleClickRouter,
    formatters,
    Toast,
    navBack,
    uniTrim,
    dayTurnTime,
    isNumber,
    useNetWork,
    isLoading,
    getHeader,
    uploadFile,
  } from "@/utils/util.js";
  import mixin from "@/utils/mixin.js";

  export default {
    name: "addFireFighting",
    mixins: [mixin],
    data() {
      return {
        baseImgUrl: this.$baseImgUrl,
        baseURL: this.$baseURL,
        form: {},
        errorType: ["none"],
        fileList: [],
        imgPrefix: uni.getStorageSync("imgPrefix"),
        dataList: [],
      };
    },
    onShow() {
      this.dataList = uni.getStorageSync("hotelDeviceDetailList") || [];
      console.log(this.dataList, "初看");
    },
    methods: {
      handleClickRouter,
      navBack,
      formatter(type, value) {
        if (type === "year") {
          return `${value}年`;
        }
        if (type === "month") {
          return `${value}月`;
        }
        if (type === "day") {
          return `${value}日`;
        }
        return value;
      },
      cellTimeClick(e) {
        this.cellType = e.currentTarget.dataset.type;
        this.maxDate = new Date(2099, 0, 1).getTime();
        var minDateNum = +new Date(); //获取当前时间的毫秒数

        switch (this.cellType) {
          case "expirationTimeName":
            this.minDate = minDateNum;
            this.timeValue = this.minDate;
            break;
          default:
            break;
        }

        setTimeout(() => {
          this.datetimeShow = true;
        }, 100);
      },
      pickerTimeClose(e) {
        if (e) {
          switch (this.cellType) {
            case "expirationTimeName":
              this.form.expirationTime = "";
              this.form.expirationTimeName = "";
              break;
            default:
              break;
          }
        }
        this.datetimeShow = false;
      },
      /* 时间选择器 确定 */
      showTimeConfirm(e) {
        let arr = e.value;
        if (arr) {
          switch (this.cellType) {
            case "expirationTimeName":
              this.form.expirationTimeName = formatters(arr, "YY/MM/DD");
              this.form.expirationTime = dayTurnTime(
                this.form.expirationTimeName
              );
              break;
            default:
              break;
          }
        }
        this.datetimeShow = false;
      },
      /* cell 点击 */
      cellClick(name, type) {
        this.keyName = name;
        this.cellType = type;
        let code = "";
        switch (this.cellType) {
          case "deviceType":
            code = "public_device_type";
            break;
          default:
            break;
        }

        findEnableDictItemsbyCode(code).then((res) => {
          this.columns[0] = res.result || [];
          this.pickerShow = true;
        });
      },
      /* 选择器 确定 */
      showConfirm(e) {
        let arr = e.value;
        if (arr.length) {
          let obj = arr[0];
          switch (this.cellType) {
            case "deviceType":
              this.form.deviceType = obj.value;
              this.form.deviceTypeDesc = obj.title;

              if (obj.value != 1) {
                this.form.deviceCount = "";
                this.form.deviceImage = [];
                this.fileList = [];
              }
              break;
            default:
              break;
          }
        }
        this.pickerShow = false;
      },
      connumBlur() {
        let {
          deviceCount
        } = this.form;
        if (deviceCount && !isNumber(deviceCount)) {
          Toast("器材数量请输入正整数");
          return;
        }
      },
      afterRead(info) {
        useNetWork(); // 判断是否有网络
        isLoading();
        let _this = this;

        uploadFile({
            url: "/web/sys/upload/upload_file",
            filePath: info.file.url,
            name: "file",
            formData: {
              type: 8,
            },
          })
          .then((res) => {
            isLoading(false);
            let {
              fullPath,
              halfPath
            } = res.result;
            _this.fileList.push({
              url: fullPath
            });
            _this.form.deviceImage = halfPath;
          })
          .finally(() => {
            isLoading(false);
          })
      },
      deletePic() {
        this.fileList = [];
        this.form.deviceImage = "";
      },
      sunmitHandle() {
        let {
          deviceType,
          deviceTypeDesc,
          deviceCount,
          deviceNo,
          expirationTime,
          expirationTimeName,
          deviceImage,
        } = this.form;

        // 1：有    0：无
        if (!deviceType) {
          Toast("请选择器材类型");
          return;
        }

        if (!deviceCount || !uniTrim(deviceCount)) {
          Toast("请输入器材数量");
          return;
        }

        if (!isNumber(deviceCount)) {
          Toast("器材数量请输入正整数");
          return;
        }

        if (!deviceImage) {
          Toast("请上传器材照片");
          return;
        }

        let data = {
          deviceType: deviceType,
          deviceTypeDesc: deviceTypeDesc,
          deviceCount: deviceCount,
          deviceNo: deviceNo || "",
          expirationTime: expirationTime || "",
          expirationTimeName: expirationTimeName || "",
          deviceImage: deviceImage,
        };

        this.dataList.push(data);
        console.log(this.dataList, "保存");
        uni.setStorageSync("hotelDeviceDetailList", this.dataList);
        Toast("保存成功");
        navBack();
      },
    },
  };
</script>

<style>
  page {
    background-color: #f3f3f3 !important;
    height: 100%;
  }
</style>
<style lang="scss" scoped>
  .addFireFighting {
    flex: 1;
    background: #f9f9f9;

    .wrapper {
      height: calc(100vh - 92px);
      margin: 20rpx;
      overflow-y: auto;

      .wrapper-item {
        padding: 20rpx;
        margin-bottom: 20rpx;
        background: #fff;

        .upload-view {
          padding-left: 30rpx;
        }
      }
    }

    .btns {
      button {
        border-radius: 44rpx;
      }
    }
  }
</style>